package com.ruoyi.web.controller.system;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.TemplateDownUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.UserInfoGroup;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.UserInfoDing;
import com.ruoyi.system.service.IUserInfoDingService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

/**
 * 钉钉用户信息Controller
 *
 * @author tjgc
 * @date 2021-04-21
 */
@RestController
@RequestMapping("/system/ding")
public class UserInfoDingController extends BaseController
{

    private static final Logger logger = LoggerFactory.getLogger(UserInfoDingController.class);

    @Autowired
    private IUserInfoDingService userInfoDingService;

    @Autowired
    private TokenService tokenService;

    /**
     * 查询钉钉用户信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:ding:list')")
    @GetMapping("/list")
    public TableDataInfo list(UserInfoDing userInfoDing)
    {
        startPage();
        List<UserInfoDing> list = userInfoDingService.selectUserInfoDingList(userInfoDing);
        return getDataTable(list);
    }

    /**
     * 导出钉钉用户信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:ding:export')")
    @Log(title = "钉钉用户信息", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(UserInfoDing userInfoDing)
    {
        List<UserInfoDing> list = userInfoDingService.selectUserInfoDingList(userInfoDing);
        ExcelUtil<UserInfoDing> util = new ExcelUtil<UserInfoDing>(UserInfoDing.class);
        return util.exportExcel(list, "ding");
    }

    /**
     * 获取钉钉用户信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:ding:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(userInfoDingService.selectUserInfoDingById(id));
    }

    /**
     * 新增钉钉用户信息
     */
    @PreAuthorize("@ss.hasPermi('system:ding:add')")
    @Log(title = "钉钉用户信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody UserInfoDing userInfoDing)
    {
        return toAjax(userInfoDingService.insertUserInfoDing(userInfoDing));
    }

    /**
     * 修改钉钉用户信息
     */
    @PreAuthorize("@ss.hasPermi('system:ding:edit')")
    @Log(title = "钉钉用户信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody UserInfoDing userInfoDing)
    {
        return toAjax(userInfoDingService.updateUserInfoDing(userInfoDing));
    }

    /**
     * 删除钉钉用户信息
     */
    @PreAuthorize("@ss.hasPermi('system:ding:remove')")
    @Log(title = "钉钉用户信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(userInfoDingService.deleteUserInfoDingByIds(ids));
    }


    /**
     * 导出钉钉用户信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:ding:import')")
    @Log(title = "钉钉用户信息", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file)  throws Exception{
        ExcelUtil<UserInfoDing> util = new ExcelUtil<UserInfoDing>(UserInfoDing.class);
        List<UserInfoDing> UserInfoDingList = util.importExcel(file.getInputStream());
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String operName = loginUser.getUser().getUserId();
        List<String> userNoList = new ArrayList<>();
        for (UserInfoDing userInfoDing:UserInfoDingList) {
            String userNo = userInfoDing.getUserNo();
            if(userNo==null||"".equals(userNo)){
                return AjaxResult.error("有人员数据工号为空，请检查修改后导入");
            }
        }
        String message = userInfoDingService.importUser(UserInfoDingList, operName,userNoList);
        return AjaxResult.success(message);
    }

    /**
     * 导出钉钉用户信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:ding:down')")
    @Log(title = "钉钉用户信息", businessType = BusinessType.IMPORT)
    @GetMapping("/templateDown")
    public void templateDown()  throws Exception{
        XSSFWorkbook xssfWorkbook = TemplateDownUtils.getXSSFWorkbook(this, "钉钉通讯录导入模板.xlsx");
        try {
            String filePass = TemplateDownUtils.createTempFile("钉钉通讯录导入模板"+ DateUtils.getDate() +".xlsx");
            logger.info("===创建的文件地址=="+filePass);
            //操作流，写入文件内容（根据前端传参）
            File tempFile = new File(filePass);
            tempFile.setExecutable(true);
            tempFile.setReadable(true);
            tempFile.setWritable(true);
            FileOutputStream outStream = new FileOutputStream(tempFile);
            xssfWorkbook.write(outStream);
            outStream.flush();
            outStream.close();
            logger.info("===文件写入完成==");
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletResponse response = servletRequestAttributes.getResponse();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            //response.setHeader("Content-Disposition", "attachment;filename=" + "contrastBOM"+ DateUtils.getDate("yyyyMMdd") +".xlsx");

            String base64Str = TemplateDownUtils.fileToBase64(filePass);
            logger.info("==导出的文件=="+base64Str);
            response.getWriter().write(base64Str);
        } catch (Exception e) {
            throw new Exception("导出失败：失败原因："+ e.getMessage());
        }
        xssfWorkbook.close();
    }



}
